package com.tourism.util;

import com.tourism.entity.RoleConstant;
import com.tourism.entity.User;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Description
 * @Author z
 * @Date 2021-03-04 21:45
 */
public class SystemHelper {

    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //有登陆用户就返回登录用户，没有就返回null
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                return (User) authentication.getPrincipal();
            }
        }

        return null;
    }

    public static Long getUserId() {
        return getCurrentUser().getId();
    }

    public static boolean isAdmin() {
        return RoleConstant.ADMIN.equals(getCurrentUser().getRole());
    }

}
